package com.sfilyh.servelt;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.sfilyh.util.DBUtil;


@WebServlet("/to_manage")
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
    public loginServlet() {
        super();
    }

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String eMessage = "";
		String sql = "select * from tb_user where username = ? and password = ?";
		String logSql = "INSERT INTO tb_logs(username,trypass,`status`) VALUES(?,?,?)";
		
		String uname =  request.getParameter("uname");
		String upwd =  request.getParameter("upwd");
		
		if(uname == null || "".equals(uname) || upwd == null || "".equals(upwd)){
			eMessage = "用户名和密码不能为空!";		
		}else if (DBUtil.countResutSize("SELECT id FROM tb_logs WHERE TO_DAYS(logintime) = TO_DAYS(NOW()) AND username=? AND STATUS = 1 ", uname) > 5 ){
			eMessage = "该账号登陆次数过多，请稍后重试!";
		}else{
			Map<String, Object> map = DBUtil.queryForMap(sql, uname,upwd);
			if(map == null){			
				DBUtil.update(logSql, uname,upwd,1);				
				eMessage = "用户名或密码错误!";
			}else{
				request.getSession().setAttribute("LOGIN", map);			
				DBUtil.update(logSql, uname,null,2);
				response.sendRedirect(request.getContextPath()+"/bz-admin/");
				return;
			}			
		}
		
		request.setAttribute("eMessage", eMessage);
		request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);
		
	}

}
